package com.mh.zookeeper.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

import static com.mh.zookeeper.PropertiesUtils.getZookeeperConnectStr;

/**
 * @author MH
 * @since 2021-12-21
 */
public class DeleteNode implements Watcher {


    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, InterruptedException {

        zooKeeper = new ZooKeeper(getZookeeperConnectStr(), 5000, new DeleteNode());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);

    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("process方法执行了 ...");
            try {
                deleteNodeSync();
            } catch (InterruptedException | KeeperException e) {
                e.printStackTrace();
            }
        }
    }

    private void deleteNodeSync() throws InterruptedException, KeeperException {

        Stat stat = zooKeeper.exists("/lg-persistent/c1", false);
        System.out.println(stat == null ? "该节点不存在" : "该节点存在");

        if (stat != null) {
            zooKeeper.delete("/lg-persistent/c1", -1);
        }

        Stat stat2 = zooKeeper.exists("/lg-persistent/c1", false);
        System.out.println(stat2 == null ? "该节点不存在" : "该节点存在");

    }
}
